package org.zhangkun.jmsg.ui.swing;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.lang.reflect.InvocationTargetException;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;

import org.zhangkun.jmsg.bean.Msg;
import org.zhangkun.jmsg.bean.User;
import org.zhangkun.jmsg.util.Res;

public class TrayDialog extends JDialog implements Runnable {
	private class ListItemLabel extends JPanel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 5151066468452085136L;
		private User user;
		private Vector<?> v;

		public ListItemLabel() {
		}

		// @Override
		public void paintComponent(Graphics g) {
			// TODO Auto-generated method stub
			super.paintComponent(g);
			FontMetrics fm = g.getFontMetrics();
			int h = fm.getHeight();
			g.drawImage(user.getPhoto(), 3, 3, h, h, this);
			g.drawString(user.getName() + "(" + (v.size() - 1) + ")", h + 6,
					3 + fm.getAscent());

		}

		public void setVector(Vector<?> v) {
			this.v = v;
			this.user = ((User) v.get(0));
			setPreferredSize(new Dimension(getFontMetrics(getFont())
					.stringWidth(user.getName()) + 40, (getFontMetrics(
					getFont()).getHeight() + 6)));
		}
	}

	private class ListItemRenderer extends ListItemLabel implements
			ListCellRenderer {

		/**
		 * 
		 */
		private static final long serialVersionUID = 3749390878558120234L;

		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {
			Vector<?> v = (Vector<?>) value;
			setVector(v);
			return this;
		}

	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 4004747351495204258L;
	private JButton delALl;
	boolean flag = true;
	private TrayIcon icon;
	private JList list;
	private DefaultListModel listModel;

	private JButton openAll;

	private long sleep;
	private boolean isRun = false;

	private JPanel space = new JPanel();
	private ListItemRenderer userInfoListItemRenderer = new ListItemRenderer();

	public TrayDialog() {
		setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);
		setAlwaysOnTop(true);
		setModal(true);

		setUndecorated(true); // 没有标题栏
		list = new JList();
		list.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				openSendDialog();
			}
		});
		list.setBorder(new TitledBorder(null, "\u672A\u8BFB\u6D88\u606F",
				TitledBorder.LEFT, TitledBorder.TOP, null, null));
		listModel = new DefaultListModel();
		list.setModel(listModel);
		list.setCellRenderer(userInfoListItemRenderer);
		JScrollPane sp = new JScrollPane(list);

		this.getContentPane().add(sp);
		this.getContentPane().add(space, BorderLayout.SOUTH);
		space.setLayout(new GridLayout(0, 2, 0, 0));

		openAll = new JButton("全部打开");
		openAll.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				openAllSendDialog();
			}
		});
		space.add(openAll);

		delALl = new JButton("全部忽略");
		delALl.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				listModel.removeAllElements();
				setVisible(false);
			}
		});
		space.add(delALl);
		this.setSize(200, 200);
		if (java.awt.SystemTray.isSupported()) {
			MainWindow.instance
					.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			try {
				icon = new TrayIcon(Res.JMSG_LOGO_IMG);
				icon.setImageAutoSize(true);
				// 创建弹出菜单
				PopupMenu menu = new PopupMenu();

				MenuItem item = new MenuItem("首选项");
				item.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						// TODO Auto-generated method stub
						SetDialog.create(MainWindow.instance);
					}
				});
				menu.add(item);
				// 添加一个用于退出的按钮
				item = new MenuItem("退出");
				item.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						MainWindow.instance.exit();
					}
				});
				menu.add(item);
				// 添加弹出菜单到托盘图标
				icon.setPopupMenu(menu);
				Dimension d = icon.getSize();
				d.setSize(d.getWidth(), d.getHeight());
				space.setPreferredSize(d);
				space.setSize(d);
				icon.addMouseMotionListener(new MouseMotionAdapter() {
					@Override
					public void mouseMoved(MouseEvent e) {
						// TODO Auto-generated method stub
						if (!TrayDialog.this.isVisible()
								&& listModel.size() > 0) {
							Point p = e.getPoint();
							Dimension size = getSize();
							p.setLocation(p.getX() - size.getWidth() / 2,
									p.getY() - size.getHeight());
							TrayDialog.this.setLocation(p);
							TrayDialog.this.setVisible(true);
							if (!isRun) {
								isRun = true;
								new Thread(TrayDialog.this,
										"Tray Icon Refresh Thread").start();
							}

						}
					}
				});
				icon.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent e) {
						// TODO Auto-generated method stub
						if (e.getClickCount() == 1) {
							MainWindow.instance.setVisible(!MainWindow.instance
									.isVisible());
							if (MainWindow.instance.isVisible())
								if (!MainWindow.instance.isActive())
									MainWindow.instance.requestFocusInWindow();
						}
						if (listModel.size() != 0)
							if (e.getClickCount() == 2) {
								openSendDialog(listModel.size() - 1);
							}
					}

				});
				SystemTray tray = SystemTray.getSystemTray();// 获取系统托盘
				tray.add(icon);// 将托盘图表添加到系统托盘

			} catch (AWTException ex) {
			}

		} else {
			MainWindow.instance.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public synchronized void addMsg(User u, Msg msg) {
		if (!isRun) {
			isRun = true;
			new Thread(this, "Tray Icon Refresh Thread").start();
		}
		Vector v = getUser(u);
		if (v == null) {
			v = new Vector();
			v.add(u);
			synchronized (listModel) {
				listModel.addElement(v);
			}
		}
		v.add(msg);
	}

	public TrayIcon getIcon() {
		return icon;
	}

	public int getSendMsgDialogIndex(User user) {
		for (int i = 0; i < listModel.size(); i++) {
			if (((User) ((Vector) listModel.get(i)).get(0)).equals(user))
				return i;
		}
		return -1;
	}

	@SuppressWarnings("rawtypes")
	public Vector getUser(User u) {
		for (int i = 0; i < listModel.size(); i++) {
			@SuppressWarnings("rawtypes")
			Vector v = ((Vector) listModel.get(i));
			if (v.get(0) == u || v.get(0).equals(u))
				return v;
		}
		return null;
	}

	public void openAllSendDialog() {
		for (int i = 0; i < listModel.size(); i++) {
			openSendDialog(i);
			i--;
		}
	}

	public void openSendDialog() {
		openSendDialog(list.getSelectedIndex());
	}

	public SendMsgDialog openSendDialog(int index) {
		setVisible(false);
		Vector<?> v = (Vector<?>) listModel.getElementAt(index);
		SendMsgDialog sd = new SendMsgDialog((User) v.get(0));
		while (!sd.isLoadFinish())
			;
		for (int i = 1; i < v.size(); i++) {
			System.out.println("addMsg " + ((Msg) v.get(i)).getMsg());
			sd.addMsg((Msg) v.get(i));
		}
		listModel.remove(index);
		MainWindow.instance.getAllSendDialog().add(sd);
		return sd;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (isRun) {
			try {
				SwingUtilities.invokeAndWait(new Runnable() {
					public void run() {
						if (isVisible()) {
							Point mp = MouseInfo.getPointerInfo().getLocation();
							Point tp = getLocationOnScreen();
							mp.setLocation(mp.getX() - tp.getX(), mp.getY()
									- tp.getY());
							if (!contains(mp)) {
								icon.setImage(Res.JMSG_LOGO_IMG);
								setVisible(false);
								repaint();
							}
							sleep = 1000;
						} else {
							if (listModel.size() != 0) {
								flag = !flag;
								if (flag) {
									Image image = ((User) ((Vector) (listModel
											.get(listModel.size() - 1))).get(0))
											.getPhoto();
									if (image != Res.JMSG_LOGO_IMG)
										icon.setImage(image);
									else {
										icon.setImage(Res.MSG_IMG);
									}
								} else {

									icon.setImage(Res.JMSG_LOGO_IMG);
								}
								sleep = 500;
								repaint();
							} else {
								isRun = false;
								icon.setImage(Res.JMSG_LOGO_IMG);
								repaint();
							}
						}

					}
				});
				if (isRun)
					Thread.sleep(sleep);
				else
					break;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void showEntryMsg(User user) {
		icon.displayMessage("用户上线",
				"用户" + user.getName() + "(IP:" + user.getIp() + ")上线啦",
				TrayIcon.MessageType.NONE);
	}

	public void showExitMsg(User user) {
		icon.displayMessage("用户下线",
				"用户" + user.getName() + "(IP:" + user.getIp() + ")下线咯",
				TrayIcon.MessageType.NONE);
	}

}
